<?php
/*
*All rights reserved: Json.
*Links:http://www.liyaoquan.cn.
*Links:http://imarkchina.cn.
*Links:http://www.imarkchina.cn.
*/

Class Template {
	Private $_template;

	Private $_vars = array();

	Public function assign($vars, $value = '') {
		if (is_array($vars)) {
			$this->_vars = array_merge($this->_vars, $vars);
		} else {
			$this->_vars[$vars] = $value;
		}
	}

	Public Static function templateFile($template) {
		if ($template == 'info') {
			return JSON_PATH.'/Common/info';
		}
		if (strstr($template, '@')) {
			$temp = str_replace('@', '', $template);
			return TEMPLATE.MODELSNAME.'/'.$temp.C('TPLSUFFIX');
		}
		return TEMPLATE.MODELSNAME.'/'.C('TPLFILE').'/'.$template.C('TPLSUFFIX');
	}

	Public Static function compileFile($template) {
		return COMPILEFILE.MODELSNAME.'/'.$template.'.Json';
	}

	Private Static function _compile($template) {
		$templateFile = self::templateFile($template);
		$compileFile = self::compileFile($template);
		if (!is_file($compileFile) || @filemtime($templateFile) > @filemtime($compileFile)) {
			if (is_file($templateFile)) {
				$content = file_get_contents($templateFile);
				$content = self::parse($content);
				J::makeDir(dirname($compileFile));
				file_put_contents($compileFile, $content);
			} else {
				throw new Exception(__METHOD__.' [找不到视图文件: '.$templateFile.']');
			}
		}
		return $compileFile;
	}

	Public Static function parse($content) {
		$ld = C('TPL_BEGIN');
		$rd = C('TPL_END');

		$content = preg_replace('/<head>/i', "<head>\r\n<meta name=\"generator\" content=\"Json\" />", $content);

                         		//模板包含模板
		$content = preg_replace('/'.$ld."tpl=(\'|\"?)(.+)\\1".$rd.'/i', "<?php include self::_compile('\\2');?>", $content);

                        		//模板包含文件
		$content = preg_replace('/'.$ld."include=(\'|\"?)(.+)\\1".$rd.'/i', "<?php include TEMPLATE.C('TPLFILE').'/\\2';?>", $content);

                        		//PHP标签
		$content = preg_replace('/'.$ld."php\s+(.+)".$rd.'/', "<?php \\1?>", $content);

                      		 //echo变量
		$content = preg_replace('/'.$ld."(\\$[a-zA-Z0-9_\x7f-\xff]*)".$rd.'/', "<?php if(isset(\\1)) echo \\1;?>", $content);

			//echo常量
		$content = preg_replace('/'.$ld."([A-Z_\x7f-\xff][A-Z0-9_\x7f-\xff]*)".$rd.'/s', "<?php if(defined('\\1')) echo \\1;?>", $content);

                       		 //echo函数
		$content = preg_replace('/'.$ld."([a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff:]*\(([^{}]*)\))".$rd.'/', "<?php echo \\1;?>", $content);

                       		 //if
		$content = preg_replace('/'.$ld."if\s+(.+?)".$rd.'/', "<?php if(\\1) { ?>", $content);

                        		//else
		$content = preg_replace('/'.$ld."else".$rd.'/', "<?php } else { ?>", $content);

                       		 //elseif
		$content = preg_replace('/'.$ld."elseif\s+(.+?)".$rd.'/', "<?php } elseif (\\1) { ?>", $content);

                       		 //end if
		$content = preg_replace('/'.$ld."\/if".$rd.'/', "<?php } ?>", $content);

                       		 //foreach
		$content = preg_replace('/'.$ld."foreach\s+(\S+)\s+(\S+)".$rd.'/', "<?php if(isset(\\1) && is_array(\\1)) foreach(\\1 as \\2) { ?>", $content);
		$content = preg_replace('/'.$ld."foreach\s+(\S+)\s+(\S+)\s+(\S+)".$rd.'/', "<?php if(is_array(\\1)) foreach(\\1 as \\2 => \\3) { ?>", $content);
		$content = preg_replace('/'.$ld."\/foreach".$rd.'/', "<?php } ?>", $content);

                        		//for
		$content = preg_replace('/'.$ld."for\s+(\S+)\s+(\S+)".$rd.'/', "<?php for(\$i=\\1; \$i < \\2; \$i++ ) { ?>", $content);
		$content = preg_replace('/'.$ld."\/for".$rd.'/', "<?php } ?>", $content);

               		 //数组引号
		$content = preg_replace_callback('/'.$ld."(\\$[a-zA-Z0-9_\[\]\'\"\$\x7f-\xff]+)".$rd.'/s', array('self', '_arrstr'), $content);
		return $content;
	}

	private static function _arrstr($matches) {
		return self::arrstr('<?php if(isset('.$matches[1].')) echo '.$matches[1].';?>');
	}

	Public Static function arrstr($string) {
		return str_replace("\\\"", "\"", preg_replace("/\[([a-zA-Z0-9_\-\.\x7f-\xff]+)\]/s", "['\\1']", $string));
	}

	Public function fetch($__template__) {
		$__file__ = self::_compile($__template__);
		if ($this->_vars) extract($this->_vars);
		ob_start();
		if (is_file($__file__)) {
			include $__file__;
			$content = ob_get_clean();
			return $content;
		}
		throw new Exception(__METHOD__.' [找不到视图编译文件: '.$__file__.']');
	}

	Public Static function getCacheFile() {
		return CACHE.'/'.C('TPLCACHENAME').'.html';
	}

	Private Static function _checkCache($cacheFile) {
		if (!is_file($cacheFile)) return false;
		return true;
	}

	Private $_readCache = false;

	Public function isCache() {
		if (!C('TPLCACHENAME')) throw new Exception(__METHOD__.' [缓存名称未设置]');
		if (!C('TPLCACHEING')) {
			Debug::add('<font color="green">'.__METHOD__.' [页面缓存未开启(\'TPLCACHEING\') 需要为真]</font>');
			return;
		}
		$this->_readCache = true;
        $cacheFile = self::getCacheFile();
        if (!self::_checkCache($cacheFile)) return false;
        return true;
	}

	Public function display($template = '') {
		if ($this->_readCache) {
			$templateFile = self::templateFile($template);
			$cacheFile = self::getCacheFile();
			if (!self::_checkCache($cacheFile)) {
				$content = $this->fetch($template);
				J::makeDir(dirname($cacheFile));
				$content = cpressHtml($content);
				file_put_contents($cacheFile, $content);
			} else {
				$content = file_get_contents($cacheFile);
			}
			echo $content;
			return;
		}
		echo $this->fetch($template);
	}

	Public function clearCache($search = '') {
		if ($search) {
			$files = glob(CACHE.'/'.$search.'.html');
			if ($files) {
				foreach ($files as $file) {
					if (is_file($file)) unlink($file);
				}
				return true;
			}
		}
		if (is_file(self::getCacheFile())) {
			if (unlink(self::getCacheFile())) {
				return true;
			}
		}
	}
}
